package cn.zf233.xcloud.service.core;

import cn.zf233.xcloud.commom.Const;
import org.springframework.stereotype.Component;

/**
 * Created by zf233 on 2021/6/19
 * 记录内存，防止溢出导致XCloud、Redis等服务死掉
 * 可根据服务器内存调整
 */
@Component("memory")
public class MemoryCoordinate {

    // 可根据服务器内存调整 cn.zf233.xcloud.common.Const.MEMORY_SIZE值（单位：MB）
    public static final long MAX = Const.MEMORY_SIZE;
    volatile private long use = 0L;

    public long left() {
        return MemoryCoordinate.MAX - this.use;
    }

    public long use() {
        return this.use;
    }

    public boolean use(long expect, long value) {
        long left = this.left();
        synchronized (this) {
            if (expect == left && left - value >= 0L) {
                this.use += value;
                return true;
            }
            return false;
        }
    }

    public boolean release(long expect, long value) {
        synchronized (this) {
            if (expect == this.left()) {
                this.use -= value;
                return true;
            }
            return false;
        }
    }

    public void reset() {
        this.use = 0L;
    }

    public static void main(String[] args) {
        System.out.println(24431713 << 3 >> 23);
    }
}